package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.teaching.domain.PlatformFForumUser;
import com.ruoyi.teaching.domain.vo.PlatformFForumUserVO;
import com.ruoyi.teaching.domain.vo.PlatformFForumVO;
import com.ruoyi.teaching.mapper.PlatformFForumUserMapper;
import com.ruoyi.teaching.service.PlatformFForumUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2025-02-17
 */
@Service
public class PlatformFForumUserServiceImpl extends ServiceImpl<PlatformFForumUserMapper, PlatformFForumUser> implements PlatformFForumUserService {
    @Autowired
    private PlatformFForumUserMapper platformFForumUserMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public AjaxResult getAllList(Integer pageNum, Integer pageSize, String nickName, String userName, Integer forumStatus) {
        Page<PlatformFForumUserVO> platformFForumUserVOPage = new Page<>(pageNum, pageSize);
        addUsersToForumUser();
        Page<PlatformFForumUserVO> forumUserVOPage = platformFForumUserMapper.selectAllList(platformFForumUserVOPage,nickName, userName, forumStatus);
        return new AjaxResult(HttpStatus.SUCCESS,"查询成功",forumUserVOPage);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult batchUpdateStatus(List<PlatformFForumUser> forumUsers) {
        int i = 0;

        for (PlatformFForumUser forumUser : forumUsers) {
            if (forumUser.getForumStatus() == 1) { // 仅对封禁的用户计算解封时间
                forumUser.setDeblockingTime(calculateDeblockingTime(forumUser.getBanType()));
            }

            int i1 = platformFForumUserMapper.updateStatusById(forumUser);
            if (i1 > 0) {
                i++;
            }
        }

        if (forumUsers.size() == i) {
            return new AjaxResult(HttpStatus.SUCCESS, "修改成功");
        }
        return new AjaxResult(HttpStatus.ERROR, "修改失败");
    }

    /**
     * 根据 banType 计算解封时间
     */
    private Date calculateDeblockingTime(Integer banType) {
        if (banType == null) {
            return null;
        }

        int daysToAdd;
        switch (banType) {
            case 0: daysToAdd = 1; break;  // 24小时
            case 1: daysToAdd = 7; break;  // 7天
            case 2: daysToAdd = 15; break; // 15天
            case 3: daysToAdd = 30; break; // 30天
            case 4: daysToAdd = 365; break; // 一年
            case 5: return null; // 永久封禁，不设置解封时间
            default: return null; // 其他非法值，不修改解封时间
        }

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, daysToAdd);
        return calendar.getTime();
    }

    @Override
    public String checkForumStatus() {
        Long userId = SecurityUtils.getUserId();
        PlatformFForumUser forumUser = platformFForumUserMapper.selectById(userId);

        if (forumUser == null) {
            PlatformFForumUser platformFForumUser = new PlatformFForumUser();
            platformFForumUser.setId(userId);
            platformFForumUserMapper.insert(platformFForumUser);
            return null;
        }

        if (forumUser.getForumStatus() == 1) {
            Date deblockingTime = forumUser.getDeblockingTime();
            Date now = new Date();

            if (deblockingTime != null) {
                if (now.after(deblockingTime)) {
                    // 解封时间已过，修改状态
                    forumUser.setForumStatus(0);
                    platformFForumUserMapper.updateStatusById(forumUser);
                    return null;
                }

                // 根据 banType 获取禁言时长文本
                String banDuration = getBanDurationText(forumUser.getBanType());

                // 格式化解封时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(forumUser.getBanType() != 5){
                    return "根据相关规定，您的账号被禁言 " + banDuration + "，将于 " + sdf.format(deblockingTime) + " 解除限制";
                }
                return "根据相关规定，您的账号被永久封禁";
            }

            return "根据相关规定，您的账号被禁言，解封时间未知";
        }

        return null;
    }

    /**
     * 根据 banType 获取禁言时长文本
     */
    private String getBanDurationText(Integer banType) {
        if (banType == null) {
            return "未知时长";
        }

        switch (banType) {
            case 0: return "24小时";
            case 1: return "7天";
            case 2: return "15天";
            case 3: return "30天";
            case 4: return "一年";
            case 5: return "永久";
            default: return "未知时长";
        }
    }


    public void addUsersToForumUser() {
        List<Long> allUserIds = platformFForumUserMapper.selectAllUserId();
        Set<Long> forumUserIds = new HashSet<>();
        if(CollectionUtils.isNotEmpty(allUserIds)){
            forumUserIds.addAll(allUserIds);
        }
        List<Long> allUserIdsSysUser = sysUserMapper.selectAllUserId();
        for (Long userId : allUserIdsSysUser) {
            if(forumUserIds.add(userId)){
                PlatformFForumUser platformFForumUser = new PlatformFForumUser();
                platformFForumUser.setId(userId);
                platformFForumUserMapper.insert(platformFForumUser);
            }
        }
    }
}
